<?php

namespace app\admin\model\yxerp;

use think\Model;

class AiConversation extends Model
{
    // 表名
    protected $name = 'yxerp_ai_conversations';
    
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    
    // 追加属性
    protected $append = [
        'model_info_array',
        'create_time_text',
        'update_time_text'
    ];
    
    // 设置模型信息
    public function setModelInfoAttr($value)
    {
        if (is_array($value)) {
            return json_encode($value);
        }
        return $value;
    }
    
    // 获取模型信息数组
    public function getModelInfoArrayAttr($value, $data)
    {
        $modelInfo = isset($data['model_info']) ? $data['model_info'] : '';
        return json_decode($modelInfo, true) ?: [];
    }
    
    // 格式化创建时间
    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ?: $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    
    // 格式化更新时间
    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ?: $data['update_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    
    // 用户关联
    public function user()
    {
        return $this->belongsTo('app\admin\model\Admin', 'user_id', 'id');
    }
    
    // 模型关联
    public function model()
    {
        return $this->belongsTo('app\admin\model\yxerp\AiModel', 'model_id', 'id');
    }
    
    // 消息关联
    public function messages()
    {
        return $this->hasMany('app\admin\model\yxerp\AiMessage', 'conversation_id', 'id')
            ->order('id ASC');
    }
    
    // 获取用户会话列表
    public static function getUserConversations($userId)
    {
        return self::where('user_id', $userId)
            ->order('last_message_time DESC, id DESC')
            ->select();
    }
    
    // 创建新会话
    public static function createConversation($data)
    {
        $conversation = new self;
        $conversation->user_id = $data['user_id'];
        $conversation->title = $data['title'];
        $conversation->model_id = $data['model_id'] ?? null;
        $conversation->model_type = $data['model_type'] ?? null;
        $conversation->model_info = $data['model_info'] ?? null;
        $conversation->message_count = 0;
        $conversation->last_message_time = date('Y-m-d H:i:s');
        $conversation->save();
        
        return $conversation;
    }
    
    // 更新会话信息
    public static function updateConversationInfo($id, $data)
    {
        $conversation = self::where('id', $id)->find();
        if (!$conversation) {
            return false;
        }
        
        if (isset($data['title'])) {
            $conversation->title = $data['title'];
        }
        
        if (isset($data['model_id'])) {
            $conversation->model_id = $data['model_id'];
        }
        
        if (isset($data['model_type'])) {
            $conversation->model_type = $data['model_type'];
        }
        
        if (isset($data['model_info'])) {
            $conversation->model_info = $data['model_info'];
        }
        
        $conversation->save();
        return $conversation;
    }
    
    // 更新消息计数
    public function updateMessageCount()
    {
        $this->message_count = $this->messages()->count();
        $this->last_message_time = date('Y-m-d H:i:s');
        $this->save();
        
        return $this;
    }
    
    // 删除会话及相关内容
    public function deleteWithRelated()
    {
        // 删除附件
        $attachments = AiAttachment::where('conversation_id', $this->id)->select();
        foreach ($attachments as $attachment) {
            $attachment->deleteFile();
            $attachment->delete();
        }
        
        // 删除消息
        AiMessage::where('conversation_id', $this->id)->delete();
        
        // 删除会话本身
        $this->delete();
        
        return true;
    }
} 